package com.twu.biblioteca.model;

import com.twu.biblioteca.controller.Movie;
import com.twu.biblioteca.controller.User;

import java.util.ArrayList;

/**
 * Created by ggoulart on 9/29/14.
 */
public class MovieDAO {

    private ArrayList<Movie> availableMovies = new ArrayList<Movie>();
    private ArrayList<UnavailableMovie> checkoutMovies = new ArrayList<UnavailableMovie>();

    private class UnavailableMovie {
        private Movie movie;
        private User user;

        protected UnavailableMovie(Movie movie, User user) {
            this.movie = movie;
            this.user = user;
        }

        protected Movie getMovie() {
            return movie;
        }

        protected User getUser() {
            return user;
        }
    }

    public MovieDAO() {
        availableMovies.add(new Movie("V for Vendetta", 2005, "James McTeigue", 8.2));
        availableMovies.add(new Movie("Ajeossi", 2010, "Jeong-beom Lee", 7.9));
    }

    public ArrayList<Movie> getAvailableMovies() {
        return availableMovies;
    }

    public Movie findMovieByName(String movieName) throws Exception {
        for (Movie movie : availableMovies) {
            if (movieName.equals(movie.getName()))
                return movie;
        }
        for (UnavailableMovie unavailableMovie : checkoutMovies) {
            if (movieName.equals(unavailableMovie.getMovie().getName()))
                return unavailableMovie.getMovie();
        }
        throw new Exception("Movie doesn't exists.");
    }

    public boolean addAvailableMovie(Movie movie) {
        return availableMovies.add(movie);
    }

    public boolean removeAvailableMovie(Movie movie) {
        return availableMovies.remove(movie);
    }

    public boolean addCheckoutMovie(Movie movie, User user) {
        return checkoutMovies.add(new UnavailableMovie(movie, user));
    }

    public boolean removeCheckoutMovie(Movie movie) throws Exception {
        return checkoutMovies.remove(getUnavailableMovie(movie));
    }

    private UnavailableMovie getUnavailableMovie(Movie movie) throws Exception {
        for(UnavailableMovie unavailableMovie : checkoutMovies) {
            if(unavailableMovie.getMovie().equals(movie))
                return unavailableMovie;
        }
        throw new Exception("Movie doesn't exists.");
    }
}
